package com.liukai.novel_commons.utils;


import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitManager {
    //    private static final RetrofitManager ourInstance = new RetrofitManager(Constans.NOVEL_BASE_URL);
    private static final RetrofitManager novelInstance = new RetrofitManager(Constans.NOVEL_BASE_URL);
    private static final RetrofitManager userInstance = new RetrofitManager(Constans.USER_BASE_URL);
    private static final RetrofitManager rackInstance = new RetrofitManager(Constans.RACK_BASE_URL);
    private final Retrofit mRetrofit;

    public static RetrofitManager getNovelInstance() {
        return novelInstance;
    }

    public static RetrofitManager getUserInstance() {
        return userInstance;
    }

    public static RetrofitManager getRackInstance() {
        return rackInstance;
    }

    private RetrofitManager(String BASEURL) {
        // 创建Retrofit
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASEURL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(genericClient())
                .build();
    }

    public Retrofit getRetrofit() {
        return mRetrofit;
    }

    public static String date = "000000"; //记录版本发布时间

    public static OkHttpClient genericClient() {
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request()
                                .newBuilder()
                                .addHeader("User-Agent", "xxxx/xxxx/" + date)
                                .build();
                        return chain.proceed(request);
                    }
                }).connectTimeout(30, TimeUnit.SECONDS).      // 设置连接超时时间
                readTimeout(30, TimeUnit.SECONDS).
                        writeTimeout(30, TimeUnit.SECONDS).build();

        return httpClient;
    }
}
